/**
 * 学生管理模块
 * 负责学生信息的增删改查操作
 */

// 学生管理类
class StudentManager {
    constructor() {
        this.students = [];
        this.loadStudents();
        this.initEventListeners();
    }

    // 从localStorage加载学生数据
    loadStudents() {
        const storedStudents = localStorage.getItem('students');
        this.students = storedStudents ? JSON.parse(storedStudents) : [];
        this.renderStudentList();
    }

    // 保存学生数据到localStorage
    saveStudents() {
        localStorage.setItem('students', JSON.stringify(this.students));
    }

    // 添加学生
    addStudent(id, name) {
        // 检查学号是否已存在
        if (this.students.some(student => student.id === id)) {
            this.showMessage('error', `学号 ${id} 已存在，请使用其他学号`);
            return false;
        }

        this.students.push({ id, name });
        this.saveStudents();
        this.renderStudentList();
        this.showMessage('success', `学生 ${name} 添加成功`);
        return true;
    }

    // 更新学生信息
    updateStudent(id, name) {
        const index = this.students.findIndex(student => student.id === id);
        if (index !== -1) {
            this.students[index].name = name;
            this.saveStudents();
            this.renderStudentList();
            this.showMessage('success', `学生 ${name} 信息更新成功`);
            return true;
        }
        return false;
    }

    // 删除学生
    deleteStudent(id) {
        const index = this.students.findIndex(student => student.id === id);
        if (index !== -1) {
            const name = this.students[index].name;
            this.students.splice(index, 1);
            this.saveStudents();
            this.renderStudentList();
            this.showMessage('success', `学生 ${name} 已删除`);
            return true;
        }
        return false;
    }

    // 根据ID获取学生
    getStudentById(id) {
        return this.students.find(student => student.id === id);
    }

    // 搜索学生
    searchStudents(query) {
        if (!query) {
            this.renderStudentList();
            return;
        }

        const filteredStudents = this.students.filter(student =>
            student.id.includes(query) || student.name.includes(query)
        );
        this.renderStudentList(filteredStudents);
    }

    // 渲染学生列表
    renderStudentList(studentList = this.students) {
        const studentListElement = document.getElementById('student-list');
        studentListElement.innerHTML = '';

        if (studentList.length === 0) {
            studentListElement.innerHTML = '<tr><td colspan="3" class="text-center">暂无学生信息</td></tr>';
            return;
        }

        studentList.forEach(student => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${student.id}</td>
                <td>${student.name}</td>
                <td>
                    <button class="btn btn-sm btn-outline-primary edit-student" data-id="${student.id}">编辑</button>
                    <button class="btn btn-sm btn-outline-danger delete-student" data-id="${student.id}">删除</button>
                </td>
            `;
            studentListElement.appendChild(row);
        });

        // 添加编辑和删除按钮的事件监听
        document.querySelectorAll('.edit-student').forEach(button => {
            button.addEventListener('click', (e) => this.handleEditStudent(e.target.dataset.id));
        });

        document.querySelectorAll('.delete-student').forEach(button => {
            button.addEventListener('click', (e) => this.handleDeleteStudent(e.target.dataset.id));
        });
    }

    // 处理编辑学生
    handleEditStudent(id) {
        const student = this.getStudentById(id);
        if (student) {
            document.getElementById('student-id').value = student.id;
            document.getElementById('student-name').value = student.name;
            document.getElementById('edit-mode').value = 'edit';
            document.getElementById('student-id').readOnly = true;
            document.getElementById('cancel-edit').style.display = 'block';
        }
    }

    // 处理删除学生
    handleDeleteStudent(id) {
        if (confirm('确定要删除这个学生吗？')) {
            this.deleteStudent(id);
        }
    }

    // 重置表单
    resetForm() {
        document.getElementById('student-form').reset();
        document.getElementById('edit-mode').value = 'add';
        document.getElementById('student-id').readOnly = false;
        document.getElementById('cancel-edit').style.display = 'none';
    }

    // 显示消息
    showMessage(type, message) {
        // 创建一个toast消息
        const toastId = 'toast-' + Date.now();
        const toastHTML = `
            <div id="${toastId}" class="toast align-items-center text-white bg-${type === 'success' ? 'success' : 'danger'}" role="alert" aria-live="assertive" aria-atomic="true">
                <div class="d-flex">
                    <div class="toast-body">
                        ${message}
                    </div>
                    <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
            </div>
        `;

        // 检查是否已存在toast容器，如果没有则创建
        let toastContainer = document.querySelector('.toast-container');
        if (!toastContainer) {
            toastContainer = document.createElement('div');
            toastContainer.className = 'toast-container position-fixed bottom-0 end-0 p-3';
            document.body.appendChild(toastContainer);
        }

        // 添加toast到容器
        toastContainer.innerHTML += toastHTML;

        // 显示toast
        const toastElement = document.getElementById(toastId);
        const toast = new bootstrap.Toast(toastElement, { delay: 3000 });
        toast.show();

        // 自动移除toast
        toastElement.addEventListener('hidden.bs.toast', () => {
            toastElement.remove();
        });
    }

    // 初始化事件监听
    initEventListeners() {
        // 表单提交事件
        document.getElementById('student-form').addEventListener('submit', (e) => {
            e.preventDefault();

            const id = document.getElementById('student-id').value.trim();
            const name = document.getElementById('student-name').value.trim();
            const editMode = document.getElementById('edit-mode').value;

            if (!id || !name) {
                this.showMessage('error', '学号和姓名不能为空');
                return;
            }

            if (editMode === 'add') {
                this.addStudent(id, name);
            } else {
                this.updateStudent(id, name);
            }

            this.resetForm();
        });

        // 取消编辑按钮
        document.getElementById('cancel-edit').addEventListener('click', () => {
            this.resetForm();
        });

        // 搜索按钮
        document.getElementById('btn-search').addEventListener('click', () => {
            const query = document.getElementById('search-student').value.trim();
            this.searchStudents(query);
        });

        // 搜索输入框回车事件
        document.getElementById('search-student').addEventListener('keyup', (e) => {
            if (e.key === 'Enter') {
                const query = e.target.value.trim();
                this.searchStudents(query);
            }
        });
    }

    // 获取所有学生
    getAllStudents() {
        return this.students;
    }
}

// 创建学生管理实例
const studentManager = new StudentManager();